<template>
  <div class="spec-preview">
    <img :src="defaultImage.imgUrl" />
    <div class="event" @mousemove="move"></div>
    <div class="big">
      <img :src="defaultImage.imgUrl" ref="bigImg"/>
    </div>
    <div class="mask" ref='mask'></div>
  </div>
</template>

<script>
  export default {
    name: "Zoom",

    props:{
      //设置默认值预防undefined报错
      skuImageList:{
        type:Array,
        //数组对象设置默认值应该使用工厂函数形式
        default:() => []
      }
    },

    data(){
      return {
        //设置用于展示的下标
        defaultIndex:0
      }
    },

    computed:{
      //设置默认值防止undefined报错
      defaultImage(){
        return this.skuImageList[this.defaultIndex] || {}
      }
    },
    
    methods:{
      //放大镜移动逻辑
      move(event){
        //获取蒙版
        const mask = this.$refs.mask
        //获取鼠标相对于容器的距离
        const {offsetX,offsetY} = event
        //计算蒙版的偏移量
        let maskX =offsetX-mask.clientWidth/2
        let maskY =offsetY-mask.clientHeight/2

        //边界值判断
        if(maskX<0){
          maskX=0
        }else if(maskX>mask.offsetWidth){
          maskX=mask.offsetWidth
        }

        if(maskY<0){
          maskY=0
        }else if(maskY>mask.offsetHeight){
          maskY=mask.offsetHeight
        }

        //赋值
        mask.style.left=maskX+'px'
        mask.style.top=maskY+'px'

        //获取大图
        const {bigImg} = this.$refs
        //赋值
        bigImg.style.left =-2*maskX +'px'
        bigImg.style.top =-2*maskY +'px'

      }
    },

    created(){
      //绑定切换图片事件
      this.$bus.$on('changeCheckImage',(activeImageIndex)=>this.defaultIndex=activeImageIndex)
    }

  }
</script>

<style lang="less">
  .spec-preview {
    position: relative;
    width: 400px;
    height: 400px;
    border: 1px solid #ccc;

    img {
      width: 100%;
      height: 100%;
    }

    .event {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      z-index: 998;
    }

    .mask {
      width: 50%;
      height: 50%;
      background-color: rgba(0, 255, 0, 0.3);
      position: absolute;
      left: 0;
      top: 0;
      display: none;
    }

    .big {
      width: 100%;
      height: 100%;
      position: absolute;
      top: -1px;
      left: 100%;
      border: 1px solid #aaa;
      overflow: hidden;
      z-index: 998;
      display: none;
      background: white;

      img {
        width: 200%;
        max-width: 200%;
        height: 200%;
        position: absolute;
        left: 0;
        top: 0;
      }
    }

    .event:hover~.mask,
    .event:hover~.big {
      display: block;
    }
  }
</style>